package cn.wubo.file.storage.demo;

import cn.wubo.file.storage.core.FileInfo;
import cn.wubo.file.storage.record.IFileStroageRecord;
import cn.wubo.sql.util.ModelSqlUtils;
import cn.wubo.sql.util.MutilConnectionPool;
import cn.wubo.sql.util.SQL;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

@Component
public class H2FileStroageRecordImpl implements IFileStroageRecord {

    static {
        MutilConnectionPool.init("main", "jdbc:h2:file:./data/demo;AUTO_SERVER=TRUE", "sa", "");
    }

    @Override
    public FileInfo save(FileInfo fileInfo) {
        FileStorageRecord fileStorageRecord = FileStorageRecord.trans(fileInfo);
        if (!StringUtils.hasLength(fileStorageRecord.getId())) {
            fileStorageRecord.setId(UUID.randomUUID().toString());
            MutilConnectionPool.run("main", conn -> ModelSqlUtils.insertSql(fileStorageRecord).executeUpdate(conn));
        } else MutilConnectionPool.run("main", conn -> ModelSqlUtils.updateSql(fileStorageRecord).executeUpdate(conn));
        return fileStorageRecord.getFileInfo();
    }

    @Override
    public List<FileInfo> list(FileInfo fileInfo) {
        FileStorageRecord fileStorageRecord = FileStorageRecord.trans(fileInfo);
        return MutilConnectionPool.run("main", conn -> ModelSqlUtils.selectSql(fileStorageRecord).executeQuery(conn)).stream().map(FileStorageRecord::getFileInfo).collect(Collectors.toList());
    }

    @Override
    public FileInfo findById(String s) {
        FileInfo query = new FileInfo();
        query.setId(s);
        List<FileInfo> list = list(query);
        return list.isEmpty() ? null : list.get(0);
    }

    @Override
    public Boolean delete(FileInfo fileInfo) {
        FileStorageRecord fileStorageRecord = FileStorageRecord.trans(fileInfo);
        return MutilConnectionPool.run("main", conn -> ModelSqlUtils.deleteSql(fileStorageRecord).executeUpdate(conn)) > 0;
    }

    @Override
    public void init() {
        if (Boolean.FALSE.equals(MutilConnectionPool.run("main", conn -> new SQL<FileStorageRecord>() {
        }.isTableExists(conn))))
            MutilConnectionPool.run("main", conn -> new SQL<FileStorageRecord>() {
        }.create().createTable(conn));
    }
}
